#include "connection.h"

Connection::Connection(QObject *parent) :
    NTcpSocket(parent)
{
    QObject::connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));
}

Connection ::~Connection()
{
}

void Connection::processReadyRead()
{
    int blockSize = 1024;
    char *buf = new char[blockSize];
    QByteArray ba(buf, sizeof(char)*blockSize);
    while(this->canReadLine())
    {
        ba = this->readLine(blockSize);
        emit readData(this->getSockType(), ba);
    }
}

void Connection::connectionError(QAbstractSocket::SocketError socketError)
{
    emit error(this);
    qDebug() << "Connection error:" << this->errorString();
}

void Connection::initConnection()
{
    if(!this->waitForReadyRead(10000))
    {
        qDebug() << "Connection error: ping timeout while initialization";
        this->close();
        return;
    }
    char buf;
    this->read(&buf,1);
    this->setSockType((sockTypes)buf);
    buf = (char)crOk;
    if(this->write(&buf,1)!=1)
    {
        qDebug() << "Connection error: error while initialization";
        this->close();
        return;
    }
    emit readyForUse(this);
}
